package com.qifenqian.turbot.module.ui.restaurant

import android.Manifest
import android.content.Context
import android.content.Intent
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback
import com.chad.library.adapter.base.listener.OnItemDragListener
import com.qifenqian.turbot.R
import com.qifenqian.turbot.base.BaseActivity
import com.qifenqian.turbot.config.Constant
import com.qifenqian.turbot.module.adapter.restaurant.PhotoAdapter
import com.qifenqian.turbot.module.adapter.itemdecoration.GridItemDecoration
import com.qifenqian.turbot.module.contract.RestaurantContract
import com.qifenqian.turbot.module.entity.request.PhotoRequest
import com.qifenqian.turbot.module.entity.response.UploadEntity
import com.qifenqian.turbot.module.entity.response.restaurant.RestaurantPhotoEntity
import com.qifenqian.turbot.module.presenter.RestaurantPresenter
import com.qifenqian.turbot.util.MyGlideEngine
import com.qifenqian.turbot.util.SpUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.internal.entity.CaptureStrategy
import kotlinx.android.synthetic.main.activity_restaurant_photo.*
import org.jetbrains.anko.toast

private const val REQUEST_RESTAURANT_IMAGE_CHOOSE = 0x89

class RestaurantPhotoActivity : BaseActivity<RestaurantPresenter, RestaurantContract.View>(), RestaurantContract.View {

    companion object {
        fun startThis(context: Context) {
            val intent = Intent(context, RestaurantPhotoActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun bindLayoutId(): Int {
        return R.layout.activity_restaurant_photo
    }

    override fun bindPresenter(): RestaurantPresenter? {
        return RestaurantPresenter(this, this)
    }

    override fun initial() {
        RxPermissions(this)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .subscribe { it1 ->
                    if (!it1) {
                        toast("没有权限")
                        finish()
                    }
                }
        mPresenter!!.getPhotoList()
        mPhotoAdapter = PhotoAdapter(mRestaurantPhotoEntities)
        rv_restaurant_photo.layoutManager = GridLayoutManager(this, 3)
        rv_restaurant_photo.addItemDecoration(GridItemDecoration(this, 8))
        rv_restaurant_photo.adapter = mPhotoAdapter
        val itemDragAndSwipeCallback = ItemDragAndSwipeCallback(mPhotoAdapter)
        val itemTouchHelper = ItemTouchHelper(itemDragAndSwipeCallback)
        itemTouchHelper.attachToRecyclerView(rv_restaurant_photo)
        mPhotoAdapter!!.enableDragItem(itemTouchHelper)
        mPhotoAdapter!!.setOnItemDragListener(object : OnItemDragListener {
            var mTargetRestaurantPhotoEntity: RestaurantPhotoEntity? = null

            override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                mTargetRestaurantPhotoEntity = mRestaurantPhotoEntities[pos]
            }

            override fun onItemDragMoving(source: RecyclerView.ViewHolder?, from: Int, target: RecyclerView.ViewHolder?, to: Int) {
            }

            override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                mRestaurantPhotoEntities.remove(mTargetRestaurantPhotoEntity)
                mRestaurantPhotoEntities.add(pos, mTargetRestaurantPhotoEntity!!)
            }
        })
        mPhotoAdapter!!.setOnDeletePhotoListener(object : PhotoAdapter.OnDeletePhotoListener {
            override fun deletePhoto(position: Int) {
                mRestaurantPhotoEntities.removeAt(position)
                mPhotoAdapter!!.notifyItemRemoved(position)
            }
        })
        btn_restaurant_photo_add.setOnClickListener {
            if (mRestaurantPhotoEntities.size < 8) {
                chooseImage(REQUEST_RESTAURANT_IMAGE_CHOOSE)
            } else {
                toast("最多只能添加8张图片")
            }
        }
        btn_restaurant_photo_next.setOnClickListener {
            val photoList = mutableListOf<PhotoRequest.Photo>()
            for (i in 0 until mRestaurantPhotoEntities.size) {
                val photo = PhotoRequest.Photo(mRestaurantPhotoEntities[i].restaurantPhotoPath)
                photoList.add(photo)
            }
            val request = PhotoRequest(SpUtils.getInstance().getInt(Constant.SP_KEY_RESTAURANT_ID, -1, Constant.SP_ACCOUNT), photoList)
            mPresenter!!.savePhotoList(request)
        }
    }

    private var mPhotoAdapter: PhotoAdapter? = null

    private var mRestaurantPhotoEntities: MutableList<RestaurantPhotoEntity> = mutableListOf()

    private fun chooseImage(requestCode: Int) {
        Matisse.from(this@RestaurantPhotoActivity)
                .choose(MimeType.ofImage())
                .countable(false)
                .capture(true)
                .captureStrategy(CaptureStrategy(true, Constant.AUTHORITY))
                .maxSelectable(8 - mRestaurantPhotoEntities.size)
                .originalEnable(true)
                .maxOriginalSize(10)
                .imageEngine(MyGlideEngine())
                .forResult(requestCode)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_RESTAURANT_IMAGE_CHOOSE && resultCode == RESULT_OK) {
            mPresenter!!.uploadFile(Matisse.obtainPathResult(data))
        }
    }

    override fun uploadFileResult(isSuccess: Boolean, code: Int, msg: String?, uploadEntity: UploadEntity?) {
        if (isSuccess) {
            val restaurantPhoneEntity = RestaurantPhotoEntity(0, uploadEntity!!.url, "", 0, 0)
            mRestaurantPhotoEntities.add(restaurantPhoneEntity)
            mPhotoAdapter!!.notifyDataSetChanged()
        }
        toast(msg!!)
    }

    override fun getPhotoListResult(isSuccess: Boolean, code: Int, msg: String?, restaurantPhotoEntities: List<RestaurantPhotoEntity>?) {
        if (isSuccess) {
            mRestaurantPhotoEntities.clear()
            mRestaurantPhotoEntities.addAll(restaurantPhotoEntities as MutableList)
            mPhotoAdapter!!.notifyDataSetChanged()
        } else {
            toast(msg!!)
        }
    }

    override fun savePhotoListResult(isSuccess: Boolean, code: Int, msg: String?) {
        if (isSuccess) {
            finish()
        }
        toast(msg!!)
    }
}
